<template>
<DialogForm ref="dialogForm"
            title="角色绑定"
            v-model="dialogVisible"
            :confirm-button="true"
            :cancel-button="true"
            :confirm-loading="confirmLoading"
            @confirm="confirmHandler"
>
  <template #content>
    <el-descriptions :column="2" border>
      <el-descriptions-item>
        <template #label>用户名</template>
        {{user.username}}
      </el-descriptions-item>
    </el-descriptions>
    <el-form style="margin-top: 20px;">
      <el-form-item label="角色" label-width="60">
        <el-select v-model="selected"
                   style="width: 240px"
                   multiple
        >
          <el-option v-for="item in options"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id"/>
        </el-select>
      </el-form-item>
    </el-form>
  </template>
</DialogForm>
</template>

<script>
import DialogForm from '@/components/dialog/DialogForm'
import { ref } from 'vue'
import { bindUserRole, deleteUserRole, getRoleListByUserId, getRoleListOptions } from '@/api/role'
import { StaticSet } from '@/utils/set'
export default {
  name: 'UserRoleForm',
  components: { DialogForm },
  setup () {
    return {
      confirmLoading: ref(false),
      dialogVisible: ref(false),
      options: ref([]),
      selected: ref([]),
      user: ref([]), // 用户id
      selectedOld: ref([])
    }
  },
  methods: {
    confirmHandler () {
      this.confirmLoading = true
      const oldSelectedSet = new StaticSet(new Set(this.selectedOld))
      const newSelectedSet = new StaticSet(new Set(this.selected))
      const difference = new StaticSet(new Set([...oldSelectedSet.difference(newSelectedSet), ...newSelectedSet.difference(oldSelectedSet)]))
      if (difference.size === 0) {
        this.dialogVisible = false
        return
      }
      const addSelectSet = [...difference.difference(oldSelectedSet)]
      const deleteSelectSet = [...difference.difference(newSelectedSet)]
      const userId = this.user.id
      this.dialogVisible = false
      bindUserRole({ userId: userId, roleIds: JSON.stringify(addSelectSet) }).then((val) => {
        console.log(val)
        deleteUserRole({ userId: userId, roleIds: JSON.stringify(deleteSelectSet) }).then((val) => {
          console.log(val)
          this.dialogVisible = this.confirmLoading = false
        })
      })
    },
    getRoleList () {
      getRoleListOptions().then(value => {
        this.options = value.data
      })
    },
    getUserRoleIds () {
      getRoleListByUserId(this.user.id).then((val) => {
        console.log(val)
        this.selected = val.data.map((val) => {
          return val.roleId
        })
        this.selectedOld = val.data.map((val) => {
          return val.roleId
        })
      })
    }
  },
  mounted () {
    this.getRoleList()
  }
}
</script>

<style scoped>

</style>
